<template>
	<div id="drawArea">
		<div class="set-s">
			<div id="konvaContainer" ref="konvaContainer"></div>
			<div v-show="positionId" class="factoiyRiskDialog" :style="{ top: positionY + 'px', left: positionX + 'px' }">
				<factoiyRiskDialog :positionId="positionId" />
			</div>
		</div>
	</div>
</template>
<script lang="ts">
import { defineComponent, reactive, ref, watch, Ref, nextTick, provide } from 'vue';
import { ElMessage } from 'element-plus';
import factoiyRiskDialog from '../component/factoiyRiskDialog.vue';
import Konva from 'konva';
// import imageBj from '/@/assets/jsc_images/icon24.png';riskBackground
// import riskBackgroundImg from '/@/assets/fac_jsc_images/icon5.png';
import imageBj from '../images/svg.png';
declare global {
	interface Window {
		saveImage: () => void;
		copyImageURL: () => void;
		openImageInNewTab: () => void;
		clearNewTab: () => void;
	}
}
export default defineComponent({
	name: 'drawArea',
	components: { factoiyRiskDialog },
	props: {
		isUseDialog: {
			type: Boolean,
			default: false,
		},
		drawInfo: {
			type: String,
			default: '',
		},
		coordinatesArr: {
			type: Array,
			default: [],
		},
	},
	setup(props, ctx) {
		let currentStatus = false;
		const titleCon = ref();
		const repeatDis = ref(false);
		const dialogVisible = ref(false);
		const konvaContainer: Ref = ref(null);
		const outBox: Ref = ref(null);
		const drawnRegions: any = ref([]); // 用于保存绘制区域的数组
		const dialogIsShow = ref(true); //是否展示弹窗
		let positionId = ref(''); //
		const positionX = ref(0); //
		const positionY = ref(0); //
		const positionOptions = reactive<Array<any>>([]); //存放位置和id数组
		provide('dialogVisible', dialogVisible);
		const definitionColor = ref([
			{ title: '低风险', color: 'rgba(64, 158, 255, 0.5)', riskLevel: 0 },
			{ title: '一般风险', color: 'rgba(255, 222, 10, 0.5)', riskLevel: 1 },
			{ title: '较大风险', color: 'rgba(255, 127, 0, 0.5)', riskLevel: 2 },
			{ title: '重大风险', color: 'rgba(245, 108, 108, 0.5)', riskLevel: 3 },
		]);
		const setColor = ref([
			{ title: '低风险', color: '#409EFF' },
			{ title: '一般风险', color: '#FFDE0A' },
			{ title: '较大风险', color: '#FF7F00' },
			{ title: '重大风险', color: '#F56C6C' },
		]);
		const showOverlay = ref(true); // 设置倒计时蒙层
		const isMapping = ref(false); // 是否可执行测绘路径操作
		const countDownSec = ref(5); // 倒计时

		const bubbleDataArray: any = ref([]); // 保存气泡数据信息
		let userPoints: any = []; // 存储用户点击的坐标点
		let layer: any = new Konva.Layer(); // 创建 Konva 层
		let bubbleLayer = new Konva.Layer(); // 创建气泡层
		let backgroundLayer = new Konva.Layer(); // 创建背景图层
		let backgroundImage: any; // 放置背景图
		let GetBool = false;
		let stage: any;
		let pos: any;
		let bubbleText: any;
		let getX: any = '';
		let getY: any = '';
		let rightCo: any = ''; // 右键坐标
		let stageWidth = 0;
		let stageHeight = 0;
		let bubbleGroup: any;
		let bubbleGroupArr: any = [];
		let globalColor: any = ''; // 设置全局颜色
		let isSubmit = true;
		let initialBubble: any = []; // 初始气泡
		let initialDrawn: any = []; // 初始区域
		let isSetColor = false;
		let isEdit = false;
		const clearCurrent = ref(false);
		let clearInx: any;
		const isAnewConfig = ref(true);

		// isPointInsidePolygon 检查一个点是否在多边形内的辅助函数
		const isPointInsidePolygon = (point: any, polygon: any) => {
			const x = point.x;
			const y = point.y;

			let inside = false;
			for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
				const xi = polygon[i].x;
				const yi = polygon[i].y;
				const xj = polygon[j].x;
				const yj = polygon[j].y;

				const intersect = yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi;

				if (intersect) {
					inside = !inside;
				}
			}
			return inside;
		};

		/*** 更新气泡文本内容 */
		const updateBubbleText = (bubbleId: any, newText: string, num: number) => {
			const bubbleData = bubbleDataArray.value.find((data: any) => data.id === bubbleId);
			if (bubbleData) {
				bubbleData.text = newText;
				// 将文本内容更新到对应气泡内
				let findArr = bubbleDataArray.value.filter((item: any) => {
					return item.id === bubbleId;
				});
				if (findArr.length !== 0) {
					bubbleText.text(newText);
					// 清除 bubbleLayer 中的所有内容
					bubbleLayer.removeChildren();
					anewDrawBubble();
					bubbleLayer.draw();
				}
			}
		};

		/*** 重新绘制气泡 */
		const anewDrawBubble = () => {
			if (bubbleDataArray.value.length !== 0) {
				bubbleGroupArr = [];
				bubbleDataArray.value.forEach((bubbleData: any, inxVal: number) => {
					// 创建气泡的背景
					const bubbleBackground = new Konva.Rect({
						width: 150, // 设置气泡的宽度
						height: 50, // 设置气泡的高度
						fill: 'lightblue', // 设置气泡的背景颜色
						cornerRadius: 4, // 设置气泡的圆角半径
					});
					// const riskBackground = new Konva.Image({
					// 	name: 'image',
					// 	image: riskBackgroundImg,
					// 	width: 50, // 设置气泡的宽度
					// 	height: 50, // 设置气泡的高度
					// });

					// 创建一个 Group 来存放气泡的内容
					bubbleGroup = new Konva.Group({
						x: bubbleData.x, // 设置气泡的 x 坐标
						y: bubbleData.y, // 设置气泡的 y 坐标
						draggable: drawnRegions.value[inxVal].isMasterRecord || drawnRegions.value[inxVal].isMasterRecord === undefined ? true : false, // 设置 Group 可拖拽
						// 可以更改 Group 的锚点（origin）来改变其相对位置的参考点。默认情况下，Group 的锚点是左上角 (0, 0)。你可以将锚点设置为左下角 (0, 1)，这样 Group 的位置将相对于其左下角定位。
						offset: {
							x: bubbleBackground.width() / 2,
							y: bubbleBackground.height() + 8, // 假设气泡的高度为50
						},
					});

					//创建提示图标
					// Konva.Image.fromURL(riskBackgroundImg, function (darthNode) {
					// 	darthNode.setAttrs({
					// 		scaleX: 0.5,
					// 		scaleY: 0.5,
					// 	});
					// 	bubbleGroup.add(darthNode);
					// });

					// 创建气泡中的文本
					bubbleText = new Konva.Text({
						text: bubbleData.text, // 设置文本内容
						fontSize: 14, // 设置字体大小
						fill: 'black', // 设置字体颜色
						align: 'center', // 设置文本对齐方式
						width: 150, // 设置文本区域的宽度
						padding: 10, // 设置文本内边距
						name: 'bubble-text', // 设置文本名称
						index: bubbleData.index, // 气泡的标识（新增的时候不需要）
					});

					// 计算三角形的位置
					const triangleX = bubbleBackground.width() / 2;
					const triangleY = bubbleBackground.height();

					// 创建三角形
					const triangle = new Konva.RegularPolygon({
						sides: 3, // 三角形的边数
						radius: 10, // 三角形的半径
						fill: 'lightblue', // 三角形的填充颜色，与气泡的背景颜色一致
						x: triangleX, // 使三角形位于气泡的中心
						y: triangleY, // 使三角形位于气泡的下方
						rotation: 180, // 旋转三角形使其倒置
					});

					// 将背景和文本添加到 Group 中
					bubbleGroup.add(bubbleBackground);
					bubbleGroup.add(bubbleText);
					bubbleGroup.add(triangle);

					let setObj: any = {};
					setObj.bubbleGroupDra = bubbleGroup;
					setObj.index = bubbleData.index;
					setObj.id = bubbleData.id;
					bubbleGroupArr.push(setObj);

					// 将 Group 添加到舞台
					bubbleLayer.add(bubbleGroup);
					// 将图层添加到舞台
					stage.add(bubbleLayer);
				});
			}
		};

		/*** 创建气泡 */
		const creatGroup = async (x: any, y: any, txt?: any) => {
			// 检查指针是否在绘制的区域内
			let clickedRegionIndex: any = '';
			if (!isAnewConfig.value) {
				let len = drawnRegions.value.length - 1;
				if (x === drawnRegions.value[len].points[0].x && y === drawnRegions.value[len].points[0].y) {
					clickedRegionIndex = len;
				} else {
					clickedRegionIndex = drawnRegions.value.findIndex((region: any) => {
						return isPointInsidePolygon(rightCo, region.points);
					});
				}
			}
			if (clickedRegionIndex !== -1 || isAnewConfig.value) {
				let bubbleIndex: any = '';
				let clickedRegionData: any = {};
				if (!isAnewConfig.value) {
					clickedRegionData = drawnRegions.value[clickedRegionIndex];
					bubbleIndex = bubbleDataArray.value.findIndex((data: any) => data.index === clickedRegionData.index);
				} else {
					bubbleIndex = -1;
					clickedRegionData.index = drawnRegions.value.length;
				}

				if (bubbleIndex !== -1) {
					updateBubbleText(bubbleDataArray.value[bubbleIndex].id, txt, bubbleIndex);
				} else {
					// 创建气泡的背景
					const bubbleBackground = new Konva.Rect({
						width: 150, // 设置气泡的宽度
						height: 50, // 设置气泡的高度
						fill: 'lightblue', // 设置气泡的背景颜色
						cornerRadius: 4, // 设置气泡的圆角半径
					});

					// 创建一个 Group 来存放气泡的内容
					bubbleGroup = new Konva.Group({
						x: x, // 设置气泡的 x 坐标
						y: y, // 设置气泡的 y 坐标
						draggable: true, // 设置 Group 可拖拽
						// 可以更改 Group 的锚点（origin）来改变其相对位置的参考点。默认情况下，Group 的锚点是左上角 (0, 0)。你可以将锚点设置为左下角 (0, 1)，这样 Group 的位置将相对于其左下角定位。
						offset: {
							x: bubbleBackground.width() / 2,
							y: bubbleBackground.height() + 8, // 假设气泡的高度为50
						},
					});

					// 创建气泡中的文本
					bubbleText = new Konva.Text({
						text: txt, // 设置文本内容
						fontSize: 14, // 设置字体大小
						fill: 'black', // 设置字体颜色
						align: 'center', // 设置文本对齐方式
						width: 150, // 设置文本区域的宽度
						padding: 10, // 设置文本内边距
						name: 'bubble-text', // 设置文本名称
						index: clickedRegionData.index,
					});

					// 计算三角形的位置
					const triangleX = bubbleBackground.width() / 2;
					const triangleY = bubbleBackground.height();

					// 创建三角形
					const triangle = new Konva.RegularPolygon({
						sides: 3, // 三角形的边数
						radius: 10, // 三角形的半径
						fill: 'lightblue', // 三角形的填充颜色，与气泡的背景颜色一致
						x: triangleX, // 使三角形位于气泡的中心
						y: triangleY, // 使三角形位于气泡的下方
						rotation: 180, // 旋转三角形使其倒置
					});

					// 将背景和文本添加到 Group 中
					bubbleGroup.add(bubbleBackground);
					bubbleGroup.add(bubbleText);
					bubbleGroup.add(triangle);

					// 保存气泡数据
					const bubbleData = {
						id: bubbleGroup._id, // 气泡的唯一标识
						x: Math.min(x),
						y: Math.min(y),
						text: txt,
						group: bubbleGroup,
						index: clickedRegionData.index,
					};

					bubbleDataArray.value.push(bubbleData);
					// bubbleGroupArr = [];
					let setObj: any = {};
					setObj.bubbleGroupDra = bubbleGroup;
					setObj.id = clickedRegionData.id;
					setObj.index = clickedRegionData.index;
					bubbleGroupArr.push(setObj);

					bubbleGroupArr.forEach((item: any, inxVal: number) => {
						// 在bubbleGroup上拖动的事件监听器
						const { bubbleGroupDra } = bubbleGroupArr[inxVal];
						bubbleGroupDra.on('dragmove', () => {
							const updatedCoordinates = {
								x: bubbleGroupDra.x(),
								y: bubbleGroupDra.y(),
							};
							// 在数组中查找被拖动的气泡索引
							const filteredData = bubbleDataArray.value.filter((data: any) => data.index === item.index);
							if (filteredData) {
								filteredData[0].x = updatedCoordinates.x;
								filteredData[0].y = updatedCoordinates.y;
								bubbleDataArray.value[item.index] = filteredData[0];
							}
						});
					});

					// 将 Group 添加到舞台
					bubbleLayer.add(bubbleGroup);
					// 将图层添加到舞台
					stage.add(bubbleLayer);
				}
			} else {
				ElMessage({
					type: 'error',
					message: '提示，未找到区域位置，无法配置气泡。',
					duration: 5000,
				});
			}
		};

		/*** 移动气泡 */
		const bubbleMove = () => {
			if (bubbleGroup && bubbleDataArray.value.length !== 0) {
				bubbleGroupArr.forEach((item: any, inxVal: number) => {
					// 在bubbleGroup上拖动的事件监听器
					const { bubbleGroupDra } = bubbleGroupArr[inxVal];
					bubbleGroupDra.on('dragmove', () => {
						const updatedCoordinates = {
							x: bubbleGroupDra.x(),
							y: bubbleGroupDra.y(),
						};

						// 在数组中查找被拖动的气泡索引
						let filteredData: any;
						filteredData = bubbleDataArray.value.filter((data: any) => data.id === item.id);
						if (filteredData.length !== 0 && bubbleDataArray.value[inxVal].id === item.id) {
							filteredData[0].x = updatedCoordinates.x;
							filteredData[0].y = updatedCoordinates.y;
							filteredData[0].group.attrs.x = updatedCoordinates.x;
							filteredData[0].group.attrs.y = updatedCoordinates.y;
							bubbleDataArray.value[item.inxVal] = filteredData[0];
						}
					});
				});
			}
		};

		/*** handleClose 关闭按钮点击事件 */
		const handleClose = () => {
			cancelUseClick();
		};

		/*** cancelUseClick 取消事件 */
		const cancelUseClick = () => {
			clearDataFun();
			ctx.emit('cancelDrawClick');
		};

		/*** 清除初始化数据 */
		const clearDataFun = () => {
			repeatDis.value = false;
			showOverlay.value = false;
			currentStatus = true;
			bubbleDataArray.value = [];
			drawnRegions.value = [];
			userPoints = [];
			getX = '';
			getY = '';
			rightCo = '';
			stageWidth = 0;
			stageHeight = 0;
			bubbleGroupArr = [];
			globalColor = '';
			countDownSec.value = 5;
			isSubmit = true;
			isSetColor = false;
			isEdit = false;
			isAnewConfig.value = true;
			initialBubble = []; // 初始气泡
			initialDrawn = []; // 初始区域
		};

		/*** 绘制坐标点 */
		const repaintCoord = () => {
			let getData = props.coordinatesArr;
			let bubbleArrList: any = [];
			let drawnArrList: any = [];

			let item = JSON.parse(props.drawInfo);
			// 设置全局颜色
			let riskVal = definitionColor.value.filter((val: any) => {
				return item.n_RiskLevel === val.riskLevel;
			});

			globalColor = riskVal[0].color;

			if (getData.length !== 0) {
				getData.map((i: any) => {
					let val = JSON.parse(i.v_Coordinates);
					if (i.id === item.id) {
						// 找到主记录的数据
						val.drawnRegions.forEach((element: any) => {
							element.isMasterRecord = true;
							element.potionId = i.id;
						});
					} else {
						val.drawnRegions.forEach((element: any) => {
							element.isMasterRecord = false;
							element.potionId = i.id;
						});
					}
					bubbleArrList = [...bubbleArrList, ...val.bubbleDataArray];
					drawnArrList = [...drawnArrList, ...val.drawnRegions];
				});
			}

			let bubbleArr = bubbleArrList;
			let drawnArr = drawnArrList;

			let setBubbleArr: any = [];
			let setDrawnArr: any = [];

			if (bubbleArr.length !== 0) {
				bubbleArr.map((i: any) => {
					let setBubbleObj: any = {};
					let groupObj: any = {};
					groupObj.attrs = {
						x: Math.round(i.group.attrs.x * stage.width()),
						y: Math.round(i.group.attrs.y * stage.height()),
						draggable: i.group.attrs.draggable,
					};
					groupObj.children = i.group.children;
					groupObj.className = i.group.className;
					setBubbleObj.group = groupObj;
					setBubbleObj.id = i.id;
					setBubbleObj.index = i.index;
					setBubbleObj.text = i.text;
					setBubbleObj.x = Math.round(i.x * stage.width());
					setBubbleObj.y = Math.round(i.y * stage.height());
					setBubbleArr.push(setBubbleObj);
				});
			}
			if (drawnArr.length !== 0) {
				drawnArr.map((i: any) => {
					let setDrawnObj: any = {};
					// setDrawnObj.color = riskVal[0].color;
					setDrawnObj.isMasterRecord = i.isMasterRecord;
					setDrawnObj.color = i.color;
					setDrawnObj.index = i.index;
					setDrawnObj.potionId = i.potionId;
					let pointsArr: any = [];
					for (let j = 0; j < i.points.length; j++) {
						let setObj: any = {};
						setObj.x = Math.round(i.points[j].x * stage.width());
						setObj.y = Math.round(i.points[j].y * stage.height());
						pointsArr.push(setObj);
					}
					setDrawnObj.points = pointsArr;
					setDrawnArr.push(setDrawnObj);
				});
			}
			bubbleDataArray.value = setBubbleArr;
			drawnRegions.value = setDrawnArr;
			setDrawnArr.map((item: any, inx: any) => {
				if (item.isMasterRecord === false) {
					initialBubble.push(JSON.parse(JSON.stringify(setBubbleArr[inx])));
					initialDrawn.push(JSON.parse(JSON.stringify(item)));
				}
			});
			drawAllRegions(); // 在画布中绘制区域
			bubbleMove(); // 移动气泡
		};

		/*** 监听isUseDialog的变化 */
		watch(
			() => props.isUseDialog,
			(newVal) => {
				if (newVal) {
					// 重置的数据
					repeatDis.value = false;
					showOverlay.value = true;
					currentStatus = true;
					bubbleDataArray.value = [];
					drawnRegions.value = [];
					userPoints = [];
					getX = '';
					getY = '';
					rightCo = '';
					stageWidth = 0;
					stageHeight = 0;
					bubbleGroupArr = [];
					globalColor = '';
					countDownSec.value = 5;
					isSubmit = true;
					isSetColor = false;
					isEdit = false;
					clearCurrent.value = false;
					isAnewConfig.value = true;
					initialBubble = []; // 初始气泡
					initialDrawn = []; // 初始区域
					countDownFun();
					let setTime = setInterval(async () => {
						if (konvaContainer.value) {
							clearDraw();
							await customFun();
							titleCon.value = '绘制区域';
							clearInterval(setTime);
						}
					}, 20);
				}
			}
		);

		/*** 倒计时函数 */
		const countDownFun = () => {
			let setTime = setInterval(() => {
				if (countDownSec.value === 0) {
					showOverlay.value = false;
					clearInterval(setTime);
				} else {
					countDownSec.value = countDownSec.value - 1;
				}
			}, 1000);
		};

		/*** 自定义函数 */
		const customFun = () => {
			nextTick(() => {
				const Timers = setInterval(() => {
					if (konvaContainer.value) {
						stageWidth = konvaContainer.value.clientWidth;
						stageHeight = konvaContainer.value.clientHeight;
						GetBool = true;
						StageFun();
						clearInterval(Timers);
					}
				}, 10);
			});
		};

		/*** clearDraw 清除全部绘制 */
		const clearDraw = () => {
			drawnRegions.value = []; // 用于保存绘制区域的数组
			userPoints = []; // 存储用户点击的坐标点
			layer.removeChildren(); // 清空舞台上的所有图像
			bubbleLayer.removeChildren(); // 清除气泡内容层
			// 重新添加 customShape
			layer.add(customShape);
			// 清除气泡数组
			bubbleDataArray.value = [];
			// 清除所有区域的时候非主记录区域不能清除
			if (initialBubble.length !== 0 && initialDrawn.length !== 0) {
				// 遍历历史中的所有区域，并绘制
				initialDrawn.map((item: any, inx: any) => {
					if (item.isMasterRecord !== undefined) {
						drawnRegions.value.push(item);
						if (initialBubble[inx]) bubbleDataArray.value.push(initialBubble[inx]);
					}
				});
				drawnRegions.value.forEach((points: any, index) => {
					// 创建 Konva 路径
					drawRegion(points, index);
				});
				// 重新绘制气泡
				anewDrawBubble();
			}
			// 更新层
			layer.draw();
			isEdit = false;
			isMapping.value = false;
		};

		/** 绘制单个区域 */
		const drawRegion = (region: any, index: number) => {
			const { points, color, potionId } = region;
			if (Array.isArray(points)) {
				// 创建 Konva 路径
				const path = new Konva.Path({
					data: getPathData(points),
					fill: color,
					stroke: 'rgba(255,255,255,0.3)',
					strokeWidth: 0.5,
					name: 'current-region-paths',
				});
				positionOptions[index + 1] = potionId;

				// 将路径添加到层
				layer.add(path);
				path.on('click', function (e: any) {
					positionId.value = positionOptions[e.target.index];
					positionX.value = e.evt.offsetX;
					positionY.value = e.evt.offsetY;
				});
			}
		};

		// 创建 Konva 自定义图形
		const customShape = new Konva.Shape({
			sceneFunc: function (context) {
				// 使用 Konva.Context 绘制自定义图形
				// 如果有用户点击的坐标点，绘制多边形
				if (userPoints.length > 0) {
					context.beginPath();
					context.moveTo(userPoints[0].x, userPoints[0].y);

					for (let i = 1; i < userPoints.length; i++) {
						context.lineTo(userPoints[i].x, userPoints[i].y);
					}

					context.closePath();

					// 设置填充颜色
					context.fillStyle = globalColor;
					context.fill();

					// 设置描边颜色和宽度
					context.strokeStyle = 'rgba(255, 255, 255, 0.3)';
					context.lineWidth = 0.5;
					context.stroke();
				}
			},
		});

		/*** 在画布中绘制保存的所有区域 */
		const drawAllRegions = () => {
			// 清空舞台上的所有图形
			layer.removeChildren();
			bubbleLayer.removeChildren(); // 清除气泡内容层

			// 重新添加 customShape如果不重新添加会出现重新绘制区域的时候能获取到坐标点但是无法重新绘制的区域无法显示在舞台上
			// 原因是做了清空舞台上的所有图形这一步操作
			layer.add(customShape);
			// 遍历历史中的所有区域，并绘制
			drawnRegions.value.forEach((points: any, index: number) => {
				// 创建 Konva 路径
				drawRegion(points, index);
			});
			// positionId.value = drawnRegions.value[0].potionId;
			// 重新绘制气泡
			anewDrawBubble();
			// 更新层
			layer.draw();
		};

		const getPathData = (points: any) => {
			// 根据坐标点生成 SVG path 数据
			return points.reduce((data: any, point: any, index: any) => {
				const command = index === 0 ? 'M' : 'L';
				return `${data} ${command} ${point.x} ${point.y}`;
			}, '');
		};

		/*** 监听窗口的变化 */
		const listenerFun = async () => {
			const resizeObserver = new ResizeObserver((entries) => {
				for (let entry of entries) {
					const { width, height } = entry.contentRect;
					// 计算舞台的缩放比例
					const scaleX = width / stageWidth;
					const scaleY = height / stageHeight;
					const newScale = Math.min(scaleX, scaleY);

					// 更新舞台的宽高和缩放比例
					stage.width(width);
					stage.height(height);
					stage.scale({ x: newScale, y: newScale });

					// 更新舞台宽高变量
					stageWidth = width;
					stageHeight = height;

					// 重新绘制舞台内容
					stage.batchDraw();
					if (backgroundImage && props.isUseDialog) {
						backgroundImage.width(width);
						backgroundImage.height(height);
						backgroundLayer.batchDraw(); // 重新绘制图层
						repaintCoord(); // 绘制坐标点
					}
				}
			});
			// 监听 konvaContainer 元素
			const konvaContainer: any = document.querySelector('#konvaContainer');
			resizeObserver.observe(konvaContainer);
		};

		/*** 设置背景图 */
		const setBjFun = () => {
			// 加载背景图片
			let imageObj = new Image();
			// 创建图片对象
			if (!backgroundImage) {
				backgroundImage = new Konva.Image({
					width: stage.width(), // 图片宽度与舞台宽度相同
					height: stage.height(), // 图片高度与舞台高度相同
					image: imageObj, // 图片对象
					draggable: false, // 禁止拖拽
				});
				// 将图片对象添加到背景图层
				backgroundLayer.add(backgroundImage);
			}

			imageObj.onload = function () {
				backgroundImage.image(imageObj as CanvasImageSource);
				backgroundLayer.draw(); // 重新绘制图层
			};
			imageObj.src = imageBj; // 背景图片路径

			// 将背景图层添加到舞台
			stage.add(backgroundLayer);
		};

		/*** 设置舞台代码 */
		const StageFun = async () => {
			if (GetBool) {
				await listenerFun();
				// 创建 Konva 舞台
				stage = new Konva.Stage({
					container: konvaContainer.value,
					width: stageWidth,
					height: stageHeight,
				});
				setBjFun();
				stage.add(layer);

				// 将自定义图形添加到层
				layer.add(customShape);

				// 更新层
				layer.draw();
			}
		};

		return {
			handleClose,
			cancelUseClick,
			titleCon,
			repeatDis,
			dialogVisible,
			clearDraw,
			outBox,
			dialogIsShow,
			positionId,
			positionY,
			positionX,
			// container,
			konvaContainer,
			definitionColor,
			setColor,
			showOverlay,
			isMapping,
			countDownSec,
			clearCurrent,
			isAnewConfig,
		};
	},
});
</script>

<style scoped lang="scss">
#drawArea {
	width: 100%;
	height: 100%;
	position: relative;

	.set-s {
		width: 100%;
		height: 100%;

		:deep(.el-dialog__body) {
			width: 100%;
			height: 100%;
			// height: calc(100vh - 110px);
			// max-height: none !important;
			// overflow-y: hidden;
		}
	}

	#konvaContainer {
		width: 100%;
		height: 100%;
	}

	.factoiyRiskDialog {
		position: absolute;
		top: 235px;
		left: 249px;
		transform: translateY(-50%);
		width: 200px;
		padding: 10px;
		box-sizing: border-box;
		border: 1px solid rgba(255, 255, 255, 0.4);
	}
}
</style>
